<template>
  <view class="change-password-page">
    <!-- 顶部导航 -->
    <view class="top-nav">
      <u-icon 
        v-if="!isForced" 
        name="arrow-left" 
        size="24" 
        color="#333" 
        @click="goBack"
      ></u-icon>
      <view class="nav-title">修改密码</view>
      <view class="nav-right"></view>
    </view>
    
    <!-- 背景装饰 -->
    <view class="bg-decorations">
      <view class="decoration-circle circle-1"></view>
      <view class="decoration-circle circle-2"></view>
      <view class="decoration-circle circle-3"></view>
    </view>
    
    <!-- 主体内容 -->
    <view class="change-password-container">
      <view class="form-header">
        <image class="lock-icon" src="/static/5G_2.png" mode="aspectFit"></image>
        <view class="form-title">
          {{ isForced ? '强制修改密码' : '修改密码' }}
        </view>
        <view class="form-subtitle">
          {{ isForced ? '检测到您使用的是初始密码，为了账户安全，请修改密码' : '请输入新的密码信息' }}
        </view>
      </view>
      
      <view class="password-form">
        <!-- 旧密码输入框 -->
        <view class="form-item">
          <view class="item-label">当前密码</view>
          <view class="input-group" :class="{'error': oldPasswordError}">
            <u-icon name="lock" size="20" color="#007aff"></u-icon>
            <u-input 
              v-model="oldPassword" 
              placeholder="请输入当前密码"
              type="password"
              password
              clearable
              @input="validateOldPassword"
            ></u-input>
          </view>
          <view class="error-tip" v-if="oldPasswordError">{{oldPasswordErrorMsg}}</view>
        </view>
        
        <!-- 新密码输入框 -->
        <view class="form-item">
          <view class="item-label">新密码</view>
          <view class="input-group" :class="{'error': newPasswordError}">
            <u-icon name="lock" size="20" color="#007aff"></u-icon>
            <u-input 
              v-model="newPassword" 
              placeholder="请输入新密码"
              type="password"
              password
              clearable
              @input="validateNewPassword"
            ></u-input>
          </view>
          <view class="error-tip" v-if="newPasswordError">{{newPasswordErrorMsg}}</view>
          
          <!-- 密码强度指示器 -->
          <view class="password-strength" v-if="newPassword">
            <view class="strength-label">密码强度：</view>
            <view class="strength-indicator">
              <view 
                class="strength-bar"
                :class="getStrengthClass()"
              ></view>
            </view>
            <view class="strength-text" :class="getStrengthClass()">
              {{ getStrengthText() }}
            </view>
          </view>
        </view>
        
        <!-- 确认密码输入框 -->
        <view class="form-item">
          <view class="item-label">确认新密码</view>
          <view class="input-group" :class="{'error': confirmPasswordError}">
            <u-icon name="lock" size="20" color="#007aff"></u-icon>
            <u-input 
              v-model="confirmPassword" 
              placeholder="请再次输入新密码"
              type="password"
              password
              clearable
              @input="validateConfirmPassword"
            ></u-input>
          </view>
          <view class="error-tip" v-if="confirmPasswordError">{{confirmPasswordErrorMsg}}</view>
        </view>
        
        <!-- 密码要求提示 -->
        <view class="password-rules">
          <view class="rules-title">密码要求：</view>
          <view class="rule-item" :class="{'valid': passwordLength >= 5}">
            <u-icon :name="passwordLength >= 5 ? 'checkmark' : 'close'" size="14" :color="passwordLength >= 5 ? '#19be6b' : '#fa3534'"></u-icon>
            <text>至少5位字符</text>
          </view>
        </view>
        
        <!-- 提交按钮 -->
        <u-button 
          type="primary" 
          class="change-btn" 
          :loading="loading" 
          :disabled="!isFormValid()"
          @click="handleChangePassword"
        >
          确认修改
        </u-button>
      </view>
    </view>
  </view>
</template>

<script>
import passwordValidator from '@/utils/password-validator.js';

export default {
  data() {
    return {
      isForced: false, // 是否强制修改密码
      oldPassword: "",
      newPassword: "",
      confirmPassword: "",
      oldPasswordError: false,
      oldPasswordErrorMsg: "",
      newPasswordError: false,
      newPasswordErrorMsg: "",
      confirmPasswordError: false,
      confirmPasswordErrorMsg: "",
      loading: false,
      passwordValidation: null // 密码验证结果
    };
  },
  
  computed: {
    // 密码长度
    passwordLength() {
      return this.newPassword.length;
    },
    
    // 是否包含小写字母
    hasLowerCase() {
      return this.passwordValidation?.checks?.lowercase?.valid || false;
    },
    
    // 是否包含大写字母
    hasUpperCase() {
      return this.passwordValidation?.checks?.uppercase?.valid || false;
    },
    
    // 是否包含数字
    hasNumber() {
      return this.passwordValidation?.checks?.number?.valid || false;
    },
    
    // 是否包含特殊字符
    hasSpecialChar() {
      return this.passwordValidation?.checks?.specialChar?.valid || false;
    },
    
    // 密码强度等级
    passwordStrength() {
      return this.passwordValidation?.strength || passwordValidator.STRENGTH_LEVELS.WEAK;
    }
  },
  
  onLoad(options) {
    // 检查是否为强制修改密码
    if (options.forced === 'true') {
      this.isForced = true;
    }
  },
  
  methods: {
    // 返回上一页
    goBack() {
      if (this.isForced) {
        // 强制修改密码时不允许返回
        uni.showToast({
          title: "请先修改密码",
          icon: "none"
        });
        return;
      }
      uni.navigateBack();
    },
    
    // 验证旧密码
    validateOldPassword() {
      if (!this.oldPassword) {
        this.oldPasswordError = true;
        this.oldPasswordErrorMsg = "请输入当前密码";
        return false;
      }
      this.oldPasswordError = false;
      return true;
    },
    
    // 验证新密码
    validateNewPassword() {
      if (!this.newPassword) {
        this.newPasswordError = true;
        this.newPasswordErrorMsg = "请输入新密码";
        this.passwordValidation = null;
        return false;
      }
      
      // 使用密码验证工具进行验证
      this.passwordValidation = passwordValidator.validatePassword(this.newPassword);
      
      if (!this.passwordValidation.valid) {
        this.newPasswordError = true;
        this.newPasswordErrorMsg = this.passwordValidation.message;
        return false;
      }
      
      // 不能与旧密码相同
      if (this.newPassword === this.oldPassword) {
        this.newPasswordError = true;
        this.newPasswordErrorMsg = "新密码不能与当前密码相同";
        return false;
      }
      
      this.newPasswordError = false;
      return true;
    },
    
    // 验证确认密码
    validateConfirmPassword() {
      const matchResult = passwordValidator.validatePasswordMatch(this.newPassword, this.confirmPassword);
      
      if (!matchResult.valid) {
        this.confirmPasswordError = true;
        this.confirmPasswordErrorMsg = matchResult.message;
        return false;
      }
      
      this.confirmPasswordError = false;
      return true;
    },
    
    // 获取密码强度样式类
    getStrengthClass() {
      if (this.passwordStrength <= passwordValidator.STRENGTH_LEVELS.WEAK) return 'weak';
      if (this.passwordStrength <= passwordValidator.STRENGTH_LEVELS.MEDIUM) return 'medium';
      if (this.passwordStrength <= passwordValidator.STRENGTH_LEVELS.STRONG) return 'strong';
      return 'very-strong';
    },
    
    // 获取密码强度文本
    getStrengthText() {
      return passwordValidator.getStrengthText(this.passwordStrength);
    },
    
    // 检查表单是否有效
    isFormValid() {
      return this.validateOldPassword() && 
             this.validateNewPassword() && 
             this.validateConfirmPassword();
    },
    
    // 处理密码修改
    handleChangePassword() {
      if (!this.isFormValid()) {
        return;
      }
      
      if (this.loading) return;
      
      this.loading = true;
      
      uni.showLoading({
        title: "修改中..."
      });
      
      // 获取用户信息
      const userInfo = JSON.parse(uni.getStorageSync('userInfo') || '{}');
      
      const requestData = {
        phone: userInfo.phone,
        oldPassword: this.oldPassword,
        newPassword: this.newPassword,
        confirmPassword: this.confirmPassword
      };
      
      this.$http.sendRequest('zhanke/user/change_password', 'POST', requestData)
        .then(res => {
          uni.hideLoading();
          this.loading = false;
          
          if (res.data && res.data.code === 200) {
            uni.showToast({
              title: "密码修改成功",
              icon: "success",
              duration: 2000,
              success: () => {
                setTimeout(() => {
                  if (this.isForced) {
                    // 强制修改密码成功后跳转到主页
                    uni.switchTab({ url: '/pages/business/index' });
                  } else {
                    // 普通修改密码成功后返回上一页
                    uni.navigateBack();
                  }
                }, 2000);
              }
            });
          } else {
            uni.showToast({
              title: res.data?.msg || "修改失败",
              icon: "error",
              duration: 2000
            });
          }
        })
        .catch(err => {
          console.error('修改密码失败', err);
          uni.hideLoading();
          this.loading = false;
          
          uni.showToast({
            title: err.errMsg || "网络请求失败",
            icon: "error",
            duration: 2000
          });
        });
    }
  }
};
</script>

<style scoped>
.change-password-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
}

/* 顶部导航 */
.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 40px 20px 20px;
  position: relative;
  z-index: 10;
}

.nav-title {
  font-size: 18px;
  font-weight: 600;
  color: #fff;
}

.nav-right {
  width: 24px;
}

/* 背景装饰 */
.bg-decorations {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.decoration-circle {
  position: absolute;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 80px;
  height: 80px;
  top: 20%;
  left: 10%;
  animation-delay: -2s;
}

.circle-2 {
  width: 60px;
  height: 60px;
  top: 40%;
  right: 15%;
  animation-delay: -4s;
}

.circle-3 {
  width: 100px;
  height: 100px;
  bottom: 30%;
  left: 20%;
  animation-delay: -1s;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}

/* 主体容器 */
.change-password-container {
  padding: 20px;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.lock-icon {
  width: 60px;
  height: 60px;
  margin-bottom: 15px;
}

.form-title {
  font-size: 24px;
  font-weight: 600;
  color: #fff;
  margin-bottom: 8px;
}

.form-subtitle {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.4;
  padding: 0 20px;
}

/* 表单样式 */
.password-form {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 25px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.form-item {
  margin-bottom: 20px;
}

.item-label {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.input-group {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  transition: all 0.3s ease;
}

.input-group:focus-within {
  border-color: #007aff;
  box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
}

.input-group.error {
  border-color: #fa3534;
  background-color: rgba(250, 53, 52, 0.05);
}

.error-tip {
  color: #fa3534;
  font-size: 12px;
  padding-left: 4px;
  margin-top: 5px;
}

u-icon {
  margin-right: 10px;
}

u-input {
  flex: 1;
  border: none;
  background: transparent;
  font-size: 14px;
}

/* 密码强度指示器 */
.password-strength {
  display: flex;
  align-items: center;
  margin-top: 10px;
  font-size: 12px;
}

.strength-label {
  color: #666;
  margin-right: 8px;
}

.strength-indicator {
  flex: 1;
  height: 4px;
  background: #e9ecef;
  border-radius: 2px;
  margin-right: 8px;
  position: relative;
  overflow: hidden;
}

.strength-bar {
  height: 100%;
  border-radius: 2px;
  transition: all 0.3s ease;
}

.strength-bar.weak {
  width: 25%;
  background: #fa3534;
}

.strength-bar.medium {
  width: 50%;
  background: #ff9500;
}

.strength-bar.strong {
  width: 75%;
  background: #19be6b;
}

.strength-bar.very-strong {
  width: 100%;
  background: #007aff;
}

.strength-text {
  font-weight: 500;
  min-width: 16px;
}

.strength-text.weak { color: #fa3534; }
.strength-text.medium { color: #ff9500; }
.strength-text.strong { color: #19be6b; }
.strength-text.very-strong { color: #007aff; }

/* 密码要求 */
.password-rules {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.rules-title {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.rule-item {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
  font-size: 12px;
  color: #999;
}

.rule-item.valid {
  color: #19be6b;
}

.rule-item u-icon {
  margin-right: 8px;
}

.rule-item:last-child {
  margin-bottom: 0;
}

/* 提交按钮 */
.change-btn {
  width: 100%;
  height: 46px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.change-btn:active {
  transform: translateY(2px);
  box-shadow: 0 2px 6px rgba(102, 126, 234, 0.3);
}

.change-btn[disabled] {
  background: #ccc !important;
  box-shadow: none !important;
  transform: none !important;
}
</style> 